<template>
  <k-form-modal
    ref="formRef"
    drawer
    width="660px"
    title="修改会员信息"
    label-width="80px"
    v-bind="formModalState"
    v-on="formModalEvent"
  >
    <div class="title">会员信息</div>
    <el-form-item label="昵称" prop="nick_name">
      <el-input v-model="state.model.nick_name" disabled placeholder="请输入用户昵称" />
    </el-form-item>

    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="state.model.mobile" disabled placeholder="请输入手机号" />
    </el-form-item>

    <el-form-item label="会员类型" prop="level" :rules="[{ required: true, message: '请选择会员类型' }]">
      <el-radio-group v-model="state.model.level">
        <el-radio v-for="item in vipLevelOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="到期时间" prop="end_time" :rules="[{ required: true, message: '请选择到期时间' }]">
      <el-date-picker
        v-model="state.model.end_time"
        style="width: 100%"
        type="date"
        :disabled-date="disabledDate"
        :shortcuts="dateShortcuts"
        placeholder="请选择到期时间"
        @change="dateChange"
      />
    </el-form-item>
    <el-form-item label="">
      <div class="quick-box">
        <div v-for="(item, i) in quickDateMap" :key="i" class="item" @click="handleClickQuickDateItem(item)">{{ item.label }}</div>
      </div>
    </el-form-item>

    <el-form-item label="封号" prop="mobile">
      <el-switch v-model="state.model.is_frozen" @change="(val) => updateRemarkByType(val ? '封号' : '', 2)" />
    </el-form-item>

    <el-form-item label="备注" prop="remark" :rules="[{ required: true, message: '请输入备注' }]">
      <el-input v-model="state.model.remark" placeholder="请输入备注" type="textarea" :rows="4" @change="resetRemarkState" />
    </el-form-item>
  </k-form-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useFormModal } from '@crud/index';
import { updateUser } from '@/api/crm-cy/user';
import { useUpdateRemark } from '@/hooks/use-update-remark';
import { quickDateMap } from '../hooks/use-table';
import { toolGetSingleDateShortCuts as dateShortcuts } from '@/utils';
import dayjs from 'dayjs';
defineOptions({ name: 'MajorCustomerEditModal' });

const formRef = ref();
const emits = defineEmits(['after-submit']);

const disabledDate = (time: Date) => {
  return;
};
const cachedData = ref();
const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  formRef,
  model: {
    id: undefined,
    level: 0,
    end_time: [],
    remark: ''
  },
  getParams: (model: any) => model,

  onShow: (mode = 0, data: any) => {
    state.model = { ...data, end_time: data.end_time && data.end_time * 1000 };
    if (data.vip_level === undefined || data.vip_level === 99) state.model.vip_level = -1;
    cachedData.value = data;
    resetRemarkState();
  },

  onSubmit: async (model: any, mode = 0) => {
    const { level, end_time, is_frozen, remark } = model;
    const params = {
      id: cachedData.value.id,
      level: level,
      end_time: dayjs(end_time).unix(),
      is_frozen: is_frozen || false,
      remark: remark
    };
    const res = await updateUser(params);
    if (!res.err) {
      ElMessage.success('编辑成功');
      emits('after-submit');
    }
    return res;
  }
});

const dateChange = (val: any) => {
  if (val) {
    state.model.end_time = dayjs(val).format('YYYY-MM-DD') + ' ' + dayjs().format('HH:ss:mm');
  }
};

/** 点击快速快速选择日期的选项的时候触发 */
const handleClickQuickDateItem = (item: any) => {
  const { value } = item;
  const [val, unit] = value;
  const cachedEndTme = cachedData.value.end_time ?? 0;

  const currentDate = dayjs().unix().valueOf();
  /** 如果到期时间已经是过期（小于今天0点，则是按过期处理），日期按当天处理（传undefined） */
  const validDate = cachedEndTme < currentDate ? undefined : cachedEndTme * 1000;
  const newDate = dayjs(validDate).add(val, unit).valueOf();
  state.model.end_time = newDate;
  if (state.model.vip_level === -1) state.model.vip_level = 0;
  updateRemarkByType(item.label, 1);
};

const { getUpdateRemarkByType, resetRemarkState } = useUpdateRemark();
const updateRemarkByType = (remark: string, type: number) => {
  state.model.remark = getUpdateRemarkByType(state.model.remark, remark, type);
};

const vipLevelOptions = [
  { label: '钻石会员', value: 20 },
  { label: '黄金会员', value: 10 },
  { label: '白银会员', value: 5 },
  { label: '体验会员', value: 0 }
];

defineExpose({
  show: methods.show
});
</script>

<style lang="scss" scoped>
.quick-box {
  display: flex;
  flex-wrap: wrap;

  .item {
    box-sizing: border-box;
    display: flex;
    gap: 4px;
    align-items: center;
    justify-content: center;
    min-width: 50px;
    height: 26px;
    padding: 0 12px;
    margin: 0 6px 0 0;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: border-color 0.3s ease;

    &:hover {
      border-color: #f1f1f1;
    }
  }
}

.title {
  margin-bottom: 20px;
}
</style>
